﻿using Dapper;
using log4net;
using MySql.Data.MySqlClient;
using StoreProject.BLL.StackBLL;
using StoreProject.DBUtil;
using StoreProject.Entity.StackEntity;
using StoreProject.Enum;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySqlHelper = StoreProject.DBUtil.MySqlHelper;

namespace StoreProject.Forms.StackForms.Operate
{
    public partial class StackAllotSettingForm : Form
    {
        ILog _log = LogManager.GetLogger("StackAllotSettingForm");
        private StackInEntity stackInEntity;
        StackLocationBLL stackLocationBLL = new StackLocationBLL();
        StackInBLL stackInBLL = new StackInBLL();
        StackLogBLL stackLogBLL = new StackLogBLL();
        public StackAllotSettingForm()
        {
            InitializeComponent();
        }
        public StackAllotSettingForm(StackInEntity stackInEntity)
        {
            this.stackInEntity = stackInEntity;
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                //判一下新旧库位是否相同
                if (this.cmbStackLocationNew.Text == this.cmbStackLocationOld.Text)
                {
                    MessageBox.Show("新旧库位不能相同！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                var newCount = Convert.ToInt32(numProductCount.Value);  //调拨的数量
                stackInEntity.Type = this.cmbType.Text;

                using (var Conn = MySqlHelper.getConnectionEx())
                {
                    MySqlTransaction trans = null;
                    try
                    {
                        Conn.Open();
                        trans = Conn.BeginTransaction();

                        //判断库存是否全部出库,全部出库直接改库位，部分出库是在原库存上做减操作，并新增一条库存信息。最后都要日志记录
                        //调拨后要判断原有库位上是否存在该货品，存在则相加


                        string sql = string.Format("select * from StackIn where id = '{0}' for update;", stackInEntity.Id);
                        //将调拨前的库位上锁
                        var readStackInEntity = Conn.QueryFirstOrDefault<StackInEntity>(sql, trans, null, null);
                        if (readStackInEntity != null && readStackInEntity.IsStack == true && readStackInEntity.ProductCount == stackInEntity.ProductCount)
                        {
                            //判断是否全部调拨
                            if (newCount == readStackInEntity.ProductCount)
                            {
                                //判断调拨后的库位是否存在
                                var isExistList = stackInBLL.GetListByWhere(string.Format("ProductName like '%{0}%'and StackLocation like '%{1}%'", this.cmbProductName.Text, this.cmbStackLocationNew.Text));
                                //不存在则直接修改原纪录
                                if (isExistList == null || isExistList.Count() == 0)
                                {
                                    var stackLocationOld = readStackInEntity.StackLocation; //旧库位
                                    string sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = true,StackLocation = '{3}' where Id = '{0}'", readStackInEntity.Id, stackInEntity.Type, newCount, this.cmbStackLocationNew.Text);
                                    int flag = Conn.Execute(sql1, trans, null, null);
                                    if (flag == 1)
                                    {
                                        StackLogEntity stackLogEntity = new StackLogEntity();
                                        stackLogEntity.Id = Guid.NewGuid().ToString();
                                        stackLogEntity.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = stackLocationOld;
                                        stackLogEntity.LogType = "1";
                                        stackLogEntity.Note = "全部调拨出库；货品：" + stackInEntity.ProductName + "从" + stackLocationOld + "全部调拨。数量为：" + newCount;
                                        stackLogEntity.CreateTime = DateTime.Now;
                                        stackLogEntity.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity);

                                        StackLogEntity stackLogEntity1 = new StackLogEntity();
                                        stackLogEntity1.Id = Guid.NewGuid().ToString();
                                        stackLogEntity1.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                                        stackLogEntity1.LogType = "0";
                                        stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "全部调拨到" + this.cmbStackLocationNew.Text + "。数量为：" + newCount;
                                        stackLogEntity1.CreateTime = DateTime.Now;
                                        stackLogEntity1.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity1);
                                    }
                                }
                                else if (isExistList != null && isExistList.Count() > 0)    //若存在则累加，并把原数据的置为false
                                {
                                    var existEntity = isExistList.ToList()[0];
                                    sql = string.Format("select * from StackIn where id = '{0}' for update;", existEntity.Id);
                                    //将调拨前的库位上锁
                                    var readStackInEntity1 = Conn.QueryFirstOrDefault<StackInEntity>(sql, trans, null, null);
                                    var oldCount = readStackInEntity1.ProductCount;    //新库位调拨前的数量

                                    var lastCount = readStackInEntity1.ProductCount + newCount; //即将更新的数量
                                    string sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = true,StackLocation = '{3}' where Id = '{0}'", readStackInEntity1.Id, stackInEntity.Type, lastCount, readStackInEntity1.StackLocation);
                                    int flag1 = Conn.Execute(sql1, trans, null, null);

                                    //将原库位置为false,库存为0
                                    sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = false where Id = '{0}'", readStackInEntity.Id, stackInEntity.Type, 0);
                                    int flag2 = Conn.Execute(sql1, trans, null, null);
                                    if (flag2 == 1 && flag1 == 1)
                                    {
                                        StackLogEntity stackLogEntity = new StackLogEntity();
                                        stackLogEntity.Id = Guid.NewGuid().ToString();
                                        stackLogEntity.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                                        stackLogEntity.LogType = "1";
                                        stackLogEntity.Note = "全部调拨出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "调拨：" + newCount;
                                        stackLogEntity.CreateTime = DateTime.Now;
                                        stackLogEntity.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity);

                                        StackLogEntity stackLogEntity1 = new StackLogEntity();
                                        stackLogEntity1.Id = Guid.NewGuid().ToString();
                                        stackLogEntity1.StackOrderId = stackInEntity.Id;
                                        stackLogEntity.StackLocation = existEntity.StackLocation;
                                        stackLogEntity1.LogType = "0";
                                        stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + existEntity.StackLocation + "。数量为：" + newCount;
                                        stackLogEntity1.CreateTime = DateTime.Now;
                                        stackLogEntity1.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity1);
                                    }
                                }
                            }
                            else
                            {
                                //判断调拨后的库位是否存在
                                var isExistList = stackInBLL.GetListByWhere(string.Format("ProductName like '%{0}%'and StackLocation like '%{1}%'", this.cmbProductName.Text, this.cmbStackLocationNew.Text));

                                if (isExistList == null || isExistList.Count() == 0)    //现库位不存在该货品，就新增一条记录
                                {
                                    StackInEntity newEntoty = new StackInEntity();
                                    newEntoty.Id = Guid.NewGuid().ToString();
                                    newEntoty.StackLocation = this.cmbStackLocationNew.Text;
                                    newEntoty.ProductCode = this.txtProductCode.Text;
                                    newEntoty.ProductName = this.cmbProductName.Text;
                                    newEntoty.ProductCount = newCount;
                                    newEntoty.UniPrice = this.numUniPrice.Value.ToString();
                                    newEntoty.Type = this.cmbType.Text;
                                    newEntoty.CreateTime = DateTime.Now;
                                    newEntoty.UpdateTime = DateTime.Now;
                                    newEntoty.IsStack = true;
                                    var flag2 = stackInBLL.Insert(newEntoty);
                                    if (flag2)
                                    {
                                        StackLogEntity stackLogEntity1 = new StackLogEntity();
                                        stackLogEntity1.Id = Guid.NewGuid().ToString();
                                        stackLogEntity1.StackOrderId = stackInEntity.Id;
                                        stackLogEntity1.StackLocation = newEntoty.StackLocation;
                                        stackLogEntity1.LogType = "0";
                                        stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + newEntoty.StackLocation + "。数量为：" + newCount;
                                        stackLogEntity1.CreateTime = DateTime.Now;
                                        stackLogEntity1.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity1);
                                    }
                                }
                                else if (isExistList != null && isExistList.Count() > 0)    //现库位存在该货品，在原有基础上累加。
                                {
                                    var existEntity = isExistList.ToList()[0];
                                    sql = string.Format("select * from StackIn where id = '{0}' for update;", existEntity.Id);
                                    //将调拨前的库位上锁
                                    var readStackInEntity1 = Conn.QueryFirstOrDefault<StackInEntity>(sql, trans, null, null);

                                    var lastCount = readStackInEntity1.ProductCount + newCount; //即将更新的数量
                                    string sql2 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = true,StackLocation = '{3}' where Id = '{0}'", readStackInEntity1.Id, stackInEntity.Type, lastCount, readStackInEntity1.StackLocation);
                                    int flag2 = Conn.Execute(sql2, trans, null, null);
                                    if (flag2 == 1)
                                    {
                                        StackLogEntity stackLogEntity1 = new StackLogEntity();
                                        stackLogEntity1.Id = Guid.NewGuid().ToString();
                                        stackLogEntity1.StackOrderId = stackInEntity.Id;
                                        stackLogEntity1.StackLocation = existEntity.StackLocation;
                                        stackLogEntity1.LogType = "0";
                                        stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + existEntity.StackLocation + "。数量为：" + newCount;
                                        stackLogEntity1.CreateTime = DateTime.Now;
                                        stackLogEntity1.UpdateTime = DateTime.Now;
                                        stackLogBLL.Insert(stackLogEntity1);
                                    }
                                }
                                //把原来库位的数量更新掉
                                var oldCount = readStackInEntity.ProductCount - newCount;
                                string sql1 = string.Format("UPDATE StackIn set Type = '{1}',ProductCount = '{2}',IsStack = true where Id = '{0}'", readStackInEntity.Id, stackInEntity.Type, oldCount);
                                int flag1 = Conn.Execute(sql1, trans, null, null);
                                if (flag1 == 1)
                                {
                                    StackLogEntity stackLogEntity = new StackLogEntity();
                                    stackLogEntity.Id = Guid.NewGuid().ToString();
                                    stackLogEntity.StackOrderId = stackInEntity.Id;
                                    stackLogEntity.StackLocation = stackInEntity.StackLocation;
                                    stackLogEntity.LogType = "1";
                                    stackLogEntity.Note = "部分调拨出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "调拨：" + newCount;
                                    stackLogEntity.CreateTime = DateTime.Now;
                                    stackLogEntity.UpdateTime = DateTime.Now;
                                    stackLogBLL.Insert(stackLogEntity);
                                }
                            }
                            trans.Commit();
                            MessageBox.Show("调拨成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            trans.Commit();
                            MessageBox.Show("调拨失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback(); //回滚
                    }
                    finally
                    {
                        trans.Dispose(); //释放
                        Conn.Close();
                        this.Close();
                    }
                }


                #region 无事务处理
                ////判一下新旧库位是否相同
                //if (this.cmbStackLocationNew.Text == this.cmbStackLocationOld.Text)
                //{
                //    MessageBox.Show("新旧库位不能相同！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                //    return;
                //}
                //var newCount = Convert.ToInt32(numProductCount.Value);  //调拨的数量
                ////判断库存是否全部出库,全部出库直接改库位，部分出库是在原库存上做减操作，并新增一条库存信息。最后都要日志记录
                ////调拨后要判断原有库位上是否存在该货品，存在则相加

                ////判断现货位上是否已存在该货品
                //var isExistList = stackInBLL.GetListByWhere(string.Format("ProductName like '%{0}%'and StackLocation like '%{1}%'", this.cmbProductName.Text, this.cmbStackLocationNew.Text));
                //if (newCount == stackInEntity.ProductCount)
                //{
                //    if (isExistList == null || isExistList.Count() == 0)    //不存在则直接修改库位即可
                //    {
                //        var stackLocationOld = stackInEntity.StackLocation; //旧库位
                //        stackInEntity.StackLocation = this.cmbStackLocationNew.Text;
                //        stackInEntity.UpdateTime = DateTime.Now;
                //        var flag = stackInBLL.Update(stackInEntity);
                //        if (flag)
                //        {
                //            StackLogEntity stackLogEntity = new StackLogEntity();
                //            stackLogEntity.Id = Guid.NewGuid().ToString();
                //            stackLogEntity.StackOrderId = stackInEntity.Id;
                //            stackLogEntity.StackLocation = stackLocationOld;
                //            stackLogEntity.LogType = "1";
                //            stackLogEntity.Note = "全部调拨出库；货品：" + stackInEntity.ProductName + "从" + stackLocationOld + "全部调拨。数量为：" + newCount;
                //            stackLogEntity.CreateTime = DateTime.Now;
                //            stackLogEntity.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity);

                //            StackLogEntity stackLogEntity1 = new StackLogEntity();
                //            stackLogEntity1.Id = Guid.NewGuid().ToString();
                //            stackLogEntity1.StackOrderId = stackInEntity.Id;
                //            stackLogEntity.StackLocation = stackInEntity.StackLocation;
                //            stackLogEntity1.LogType = "0";
                //            stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "全部调拨到" + stackInEntity.StackLocation + "。数量为：" + newCount;
                //            stackLogEntity1.CreateTime = DateTime.Now;
                //            stackLogEntity1.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity1);
                //        }
                //    }
                //    else if (isExistList != null && isExistList.Count() > 0)    //若存在则累加，并把原数据的置为false
                //    {
                //        var existEntity = isExistList.ToList()[0];
                //        var oldCount = existEntity.ProductCount;    //新库位调拨前的数量
                //        existEntity.ProductCount = existEntity.ProductCount + newCount;
                //        var flag = stackInBLL.Update(existEntity);

                //        stackInEntity.IsStack = false;
                //        stackInEntity.ProductCount = 0;
                //        var flag1 = stackInBLL.Update(stackInEntity);
                //        if (flag && flag1)
                //        {
                //            StackLogEntity stackLogEntity = new StackLogEntity();
                //            stackLogEntity.Id = Guid.NewGuid().ToString();
                //            stackLogEntity.StackOrderId = stackInEntity.Id;
                //            stackLogEntity.StackLocation = stackInEntity.StackLocation;
                //            stackLogEntity.LogType = "1";
                //            stackLogEntity.Note = "全部调拨出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "调拨：" + newCount;
                //            stackLogEntity.CreateTime = DateTime.Now;
                //            stackLogEntity.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity);

                //            StackLogEntity stackLogEntity1 = new StackLogEntity();
                //            stackLogEntity1.Id = Guid.NewGuid().ToString();
                //            stackLogEntity1.StackOrderId = stackInEntity.Id;
                //            stackLogEntity.StackLocation = existEntity.StackLocation;
                //            stackLogEntity1.LogType = "0";
                //            stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + existEntity.StackLocation + "。数量为：" + newCount;
                //            stackLogEntity1.CreateTime = DateTime.Now;
                //            stackLogEntity1.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity1);
                //        }
                //    }
                //}
                //else
                //{
                //    //把原来库位的数量更新掉
                //    stackInEntity.ProductCount = stackInEntity.ProductCount - newCount;
                //    var flag = stackInBLL.Update(stackInEntity);
                //    if (flag)
                //    {
                //        StackLogEntity stackLogEntity = new StackLogEntity();
                //        stackLogEntity.Id = Guid.NewGuid().ToString();
                //        stackLogEntity.StackOrderId = stackInEntity.Id;
                //        stackLogEntity.StackLocation = stackInEntity.StackLocation;
                //        stackLogEntity.LogType = "1";
                //        stackLogEntity.Note = "部分调拨出库；货品：" + stackInEntity.ProductName + "从" + stackInEntity.StackLocation + "调拨：" + newCount;
                //        stackLogEntity.CreateTime = DateTime.Now;
                //        stackLogEntity.UpdateTime = DateTime.Now;
                //        stackLogBLL.Insert(stackLogEntity);
                //    }

                //    if (isExistList == null || isExistList.Count() == 0)    //现库位不存在该货品，就新增一条记录
                //    {
                //        StackInEntity newEntoty = new StackInEntity();
                //        newEntoty.Id = Guid.NewGuid().ToString();
                //        newEntoty.StackLocation = this.cmbStackLocationNew.Text;
                //        newEntoty.ProductCode = this.txtProductCode.Text;
                //        newEntoty.ProductName = this.cmbProductName.Text;
                //        newEntoty.ProductCount = newCount;
                //        newEntoty.UniPrice = this.numUniPrice.Value.ToString();
                //        newEntoty.Type = this.cmbType.Text;
                //        newEntoty.CreateTime = DateTime.Now;
                //        newEntoty.UpdateTime = DateTime.Now;
                //        newEntoty.IsStack = true;
                //        var flag1 = stackInBLL.Insert(newEntoty);
                //        if (flag1)
                //        {
                //            StackLogEntity stackLogEntity1 = new StackLogEntity();
                //            stackLogEntity1.Id = Guid.NewGuid().ToString();
                //            stackLogEntity1.StackOrderId = stackInEntity.Id;
                //            stackLogEntity1.StackLocation = newEntoty.StackLocation;
                //            stackLogEntity1.LogType = "0";
                //            stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + newEntoty.StackLocation + "。数量为：" + newCount;
                //            stackLogEntity1.CreateTime = DateTime.Now;
                //            stackLogEntity1.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity1);
                //        }
                //    }
                //    else if (isExistList != null && isExistList.Count() > 0)    //现库位存在该货品，在原有基础上累加。
                //    {
                //        var existEntity = isExistList.ToList()[0];
                //        existEntity.ProductCount = existEntity.ProductCount + newCount;
                //        var flag1 = stackInBLL.Update(existEntity);
                //        if (flag1)
                //        {
                //            StackLogEntity stackLogEntity1 = new StackLogEntity();
                //            stackLogEntity1.Id = Guid.NewGuid().ToString();
                //            stackLogEntity1.StackOrderId = stackInEntity.Id;
                //            stackLogEntity1.StackLocation = existEntity.StackLocation;
                //            stackLogEntity1.LogType = "0";
                //            stackLogEntity1.Note = "调拨入库；货品：" + stackInEntity.ProductName + "部分调拨到" + existEntity.StackLocation + "。数量为：" + newCount;
                //            stackLogEntity1.CreateTime = DateTime.Now;
                //            stackLogEntity1.UpdateTime = DateTime.Now;
                //            stackLogBLL.Insert(stackLogEntity1);
                //        }
                //    }
                //}
                #endregion
                
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
                this.Close();
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void StackAllotSettingForm_Load(object sender, EventArgs e)
        {
            if (stackInEntity != null)
            {
                this.cmbProductName.Text = stackInEntity.ProductName;
                this.txtProductCode.Text = stackInEntity.ProductCode;
                this.cmbStackLocationOld.Text = stackInEntity.StackLocation;
                this.numUniPrice.Value = Convert.ToDecimal(stackInEntity.UniPrice);
                this.numProductCount.Maximum = stackInEntity.ProductCount;

                var list1 = stackLocationBLL.GetList().OrderByDescending(x => x.UpdateTime).ToList().Select(x => x.StackName).ToArray();
                this.cmbStackLocationNew.Items.AddRange(list1);
                List<string> typeList = new List<string>();
                typeList.Add("调拨");
                this.cmbType.Items.AddRange(typeList.ToArray());
                this.cmbType.SelectedIndex = 0;
            }
        }
    }
}
